<template>
  <div class="container top-0 position-sticky z-index-sticky">
    <div class="row">
      <div class="col-12">
        <top-navbar           
          isBlur="blur  border-radius-lg my-3 py-2 start-0 end-0 mx-4 shadow"
          v-bind:darkMode="true"
          isBtn="bg-gradient-success"/>
      </div>
    </div>
  </div>
  <main class="main-content mt-0">
    <div
      class="page-header align-items-start min-vh-50 pt-5 pb-11 m-3 border-radius-lg signup"
      style="background-position: top;"
    >
      <span class="mask bg-gradient-dark opacity-6 "></span>
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-lg-5 text-center mx-auto">
            <h1 class="text-white mb-2 mt-5">Welcome!</h1>
            <p
              class="text-lead text-white"
            >Use these awesome forms to login or create new account in your project for free.</p>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="row mt-lg-n10 mt-md-n11 mt-n10 justify-content-center">
        <div class="col-xl-4 col-lg-5 col-md-7 mx-auto">
          <div class="card z-index-0">
            <div class="card-body">
              <form @submit="isSubmit($event)">
                <argon-signup-input type="email" placeholder="Email" aria-label="Email" isRequired="true" v-model="signup_form.email" info="info"/>
                <p>
                {{emailInfo}}
                </p>
                  <div class="input-group mb-3">
                    <input type="text" class="form-control" placeholder="Your Email" v-model="signup_form.captcha">
                    <el-button size="large" type="info" class="input-group-text btn-secondary" v-show="show" @click="sendPin" round>Send</el-button>
                    <el-button size="large" type="info" class="input-group-text btn-secondary" v-show="!show" round>{{" "+count+"s"}}</el-button>
                  </div>
                <argon-signup-input type="text" placeholder="Name" aria-label="Name" isRequired=true  v-model="signup_form.user_name" />
                <argon-signup-input type="password" placeholder="Password" aria-label="Password" isRequired=true  v-model="signup_form.pwd"/>
                <argon-signup-input type="password" placeholder="Confirm Password" aria-label="Password" isRequired=true  v-model="signup_form.confirm_pwd"/>
                <div class="text-center" >
                  <argon-signup-button fullWidth color="dark" variant="gradient" class="my-4 mb-2" @click="register">Sign up</argon-signup-button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <button @click="getCookie">get cookie</button> -->
  </main>
  <app-footer />
</template>

<script>
import TopNavbar from "@/examples/PageLayout/TopNavbar.vue";
import AppFooter from "@/examples/PageLayout/Footer.vue";
import ArgonSignupInput from "@/components/ArgonSignupInput.vue";
import ArgonSignupButton from "@/components/ArgonSignupButton.vue";
// import ArgonBadge from "@/components/ArgonBadge.vue";
import axios from "axios"
import router from "@/router/index.js"
import {useCookies} from "vue3-cookies"
import { ElButton } from 'element-plus';

const {cookies} = useCookies();
const body = document.getElementsByTagName("body")[0];

export default {
  name: "signup",
  components: {
    TopNavbar,
    AppFooter,
    ArgonSignupInput,
    ArgonSignupButton,
    ElButton
    // ArgonBadge
  },
  data(){
    return {
      //路由：https://fitzone.work:8080/post
      signup_form:{
        user_name:'',
        email:'',
        pwd:'',
        confirm_pwd:'',
        captcha:''
      },

      checkFlag:0,   //0：不提交 1：提交 （是否跳转）
      submitFlag:0,  //0：不提交 1：提交 （是否提交表单） 
      captchaFlag:'I dont konw',
      CAPTCHA:0,

      emailVertifi:0,
      captchaVertifi:0,
      usernameVertifi:0,
      pwdVervifi:0,
      confirm_pwdVertifi:0,
      timer:null,
      show:true,
      count:'',
      emailInfo:'',
      captchaInfo:'',
      usernameInfo:'',
      pwdInfo:'',
      
      
    }
  },
  watch:{
    //用户名输入校验
    'signup_form.user_name'(newUserName){
      let len = newUserName.length
      if(len < 6){
        this.usernameInfo = "User name must be more than six characters!"
      }
      else{
        this.usernameInfo =""
        this.usernameVertifi = 1
      }
    },
    //密码输入校验
    'signup_form.pwd'(newpwd){
      let len = newpwd.length
      if(len < 6){
        this.pwdInfo = "Password must be more than six characters!"
      }
      else{
        this.pwdInfo = ""
        this.pwdVervifi = 1
      }
    },
    //密码再次输入校验
    'signup_form.confirm_pwd'(newconfirm_pwd){
      if(newconfirm_pwd != this.signup_form.pwd){
        this.pwdInfo = "The two password entries should be consistent"
      }
      else{
        this.pwdInfo=""
        this.confirm_pwdVertifi = 1
      }
    },
    //邮箱输入校验
    'signup_form.email'(newemail){
      let len = newemail.length
      if(len == 0){
        this.emailInfo = "Please enter your E-mail!"
      }
      else{
        this.emailInfo = ""
        this.emailVertifi = 1
      }
    },
    // 验证码输入校验
    'signup_form.email.captcha'(newcaptcha){
      console.log("type into is "+ newcaptcha)
      console.log("cookie is" + cookies.get("CAPTCHA"))
      if(cookies.get("CAPTCHA") != newcaptcha){
        this.captchaInfo = "Please enter valid captcha"
      }
      else{
        this.captchaInfo = ""
        this.captchaVertifi = 1
      }
    },
    immediate:true
  },
  methods: {
    register_check(){
      let check = 0

      // check += this.emailVertifi
      check += this.usernameVertifi
      check += this.pwdVervifi
      check += this.confirm_pwdVertifi
      if(this.signup_form.captcha == cookies.get("CAPTCHA")){
        check += 1
      }
      if(check == 4){
        return true
      }
      else{
        return false
      }
    },
    register(){
      console.log(this.register_check())
      if(this.signup_form.captcha != cookies.get("CAPTCHA")){
        alert("Invalid Captcha")
        console.log("Yes InValid!")
      }
      if(this.register_check()){
        console.log(this.signup_form)
        axios({
          method:'get',
          baseURL: 'https://fitzone.work:8080/register',
          params:{
          email:this.signup_form.email, 
          captcha:this.signup_form.captcha, 
          user_name:this.signup_form.user_name,
          pwd:this.signup_form.pwd 
          }
        }).then(res=>{
          //console.log(res)
          if(res.data=="-2"){
            alert("The username has been registered, please change another!")
            this.checkFlag = 0
          }else if(res.data=="-1"){
            alert("Email has already registered. Please login!")
            this.checkFlag = 0
          } 
          else if(res.data =="0"){
            this.checkFlag = 1
            router.push('/signin')
          }
        })
        .catch(err=>{
          console.log(err)
        }) 
      }else{
        this.checkFlag = 0
      }
    },
    countDown(){
        const TIME_COUNT = 60;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
          }, 1000)
        }
    },
    sendPin(){
      let formData = new FormData()
      formData.append("email",this.signup_form["email"])
      if(this.signup_form.email.length == 0)
      {
        this.emailInfo = "Please enter your E-mail!"
      }
      else{
        axios({
          method:'get',
          baseURL: 'https://fitzone.work:8080/register',
          params:{
          email:this.signup_form.email,   
          }
        }).then(res=>{
          // console.log(res)
          if(res.data == "-1"){
            alert("Email has already registered. Please login!")
          }
          else{
            this.CAPTCHA = res.data
            console.log(res.data)
            cookies.set("CAPTCHA",this.CAPTCHA,'300s')
            this.submitFlag = 0
            this.countDown()
          }
        }) 
      }
    },
    getCookie(){
      cookies.get("CAPTCHA")   
    },
    isSubmit(e){
      if(this.checkFlag == 0){
        return e.preventDefault();
      }
    }
  },
  created() {
    this.$store.state.hideConfigButton = true;
    this.$store.state.showNavbar = false;
    this.$store.state.showSidenav = false;
    this.$store.state.showFooter = false;
    body.classList.remove("bg-gray-100");
  },
  beforeUnmount() {
    this.$store.state.hideConfigButton = false;
    this.$store.state.showNavbar = true;
    this.$store.state.showSidenav = true;
    this.$store.state.showFooter = true;
    body.classList.add("bg-gray-100");
  },

};
</script>
<style>
.signup{
  background-image:url('./../assets/img/login.jpg');
}
</style>